package com.heima.gateway.app.filter;

import com.heima.gateway.app.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * app全局登录验证
 * @data 2024 9:29
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取当前的请求路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().toString();
        log.info("接收到客户端请求：{}",path);
        //2. 判断是否是登录相关的资源请求，如果是就直接放行
        if (path.contains("login")){
            return chain.filter(exchange);
        }
        //3. 不是则需要进一步获取token
        HttpHeaders headers = request.getHeaders();
        try {
            List<String> list = headers.get("Token");
            String token = list.get(0);
            //4. 验证token是否有效
            //4.2 再验证token是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int res = AppJwtUtil.verifyToken(claimsBody);
            //5. 有效：放行; 无效：返回401
            if (res == -1 || res == 0){
                //有效：放行
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //无效：返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);    //设置响应状态码
        return response.setComplete();//立即响应到客户端;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
